package com.xyh.transaction.config;

import com.xyh.transaction.exception.LoginException;
import com.xyh.transaction.service.imp.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // TODO 验证码校验
//        String captcha = request.getParameter("captcha"); // 验证码
//        if (validateCaptcha(captcha)) {
//            // 抛出验证码异常
//        }

        // 根据用户名从数据库中获取用户信息（示例中未实际从数据库中获取）
        UserDetails loginUser = userDetailsService.loadUserByUsername(username);

        // 检查密码是否匹配
        if (!passwordEncoder.matches(password, loginUser.getPassword())) {
            throw new LoginException("密码错误");
        }

        // 判断状态
        if (!loginUser.isEnabled()) {
            throw new LoginException("账号被禁用!");
        }

        // 返回认证成功的令牌
        return new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }


    private boolean validateCaptcha(String inputCaptcha) {
        // 根据实际情况验证验证码，可以从session中获取生成的验证码进行比对
        // 验证码可以存储：1.session 2.缓存（redis） 3.数据库 4.cookie 5.token
        // 这里只是一个简单的示例，实际中可能需要更复杂的实现
        String storedCaptcha = (String) request.getSession().getAttribute("captcha");
        return inputCaptcha != null && inputCaptcha.equalsIgnoreCase(storedCaptcha);
    }
}
